package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

// AuthMiddleware JWT认证中间件
func AuthMiddleware(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		//authHeader := c.GetHeader("Authorization")
		//if authHeader == "" {
		//	c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供授权令牌"})
		//	c.Abort()
		//	return
		//}
		//
		//// 检查Bearer前缀
		//parts := strings.SplitN(authHeader, " ", 2)
		//if !(len(parts) == 2 && parts[0] == "Bearer") {
		//	c.JSON(http.StatusUnauthorized, gin.H{"error": "授权令牌格式错误"})
		//	c.Abort()
		//	return
		//}
		//
		//// 解析JWT令牌
		//claims := &Claims{}
		//token, err := jwt.ParseWithClaims(parts[1], claims, func(token *jwt.Token) (interface{}, error) {
		//	return []byte(secret), nil
		//})
		//
		//if err != nil || !token.Valid {
		//	c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的授权令牌"})
		//	c.Abort()
		//	return
		//}
		//
		//// 验证用户是否存在
		//var user model.User
		//if err := utils.DB.First(&user, claims.UserID).Error; err != nil {
		//	c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
		//	c.Abort()
		//	return
		//}
		//
		//// 将用户ID存入上下文
		//c.Set("userID", claims.UserID)
		c.Set("userID", 1)
		c.Next()
	}
}

// Claims JWT载荷
type Claims struct {
	UserID uint `json:"user_id"`
	jwt.RegisteredClaims
}
